package com.offcn.bigdata.spark;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.function.VoidFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;

public class JavaSparkWordCountLambdaApp {
    public static void main(String[] args) {
        //step 1
        SparkConf conf = new SparkConf();
        conf.setMaster("local[*]");
        conf.setAppName(JavaSparkWordCountLambdaApp.class.getSimpleName());

        JavaSparkContext jsc = new JavaSparkContext(conf);

        //step 2 加载数据
        JavaRDD<String> lines = jsc.textFile("E:/data/spark/hello.txt");
        System.out.println("partition: " + lines.getNumPartitions());
        //step 3 transformation变换操作
//        JavaRDD<String> words = lines.flatMap((String line) -> {
//            String[] fields = line.split("\\s+");
//            return Arrays.asList(fields).iterator();
//        });
        JavaRDD<String> words = lines.flatMap(line -> Arrays.asList(line.split("\\s+")).iterator());

        JavaPairRDD<String, Integer> pairs = words.mapToPair(word -> new Tuple2<String, Integer>(word, 1));

        JavaPairRDD<String, Integer> ret = pairs.reduceByKey((v1, v2) -> v1 + v2);

        // step 4 action触发作业
        ret.foreach(t -> System.out.println(t._1 + "---" + t._2));

        //step 5
        jsc.close();
    }
}
